<template>
  <div>
    <div class="fundodoo-pic-selector-button-preview">
      <div class="fundodoo-pic-selected-preview-container">
        <div v-for="(item) in finalSelected" :key="item.id" class="fundodoo-pic-selected-preview-item">
          <el-image class="fundodoo-pic-selected-preview" fit="scale-down" :src="item.value">
            <div slot="error" class="fundodoo-image-load-error">
              <i class="el-icon-picture-outline" />
            </div>
          </el-image>
          <div class="fundodoo-preview-actions-container-modal" />
          <div class="fundodoo-preview-actions-container">
            <i class="el-icon-view fundodoo-preview-action fundodoo-cursor" @click="previewSelected" />
            <i class="el-icon-delete fundodoo-preview-action fundodoo-cursor" style="margin-left:5px;" @click="delSelected(item)" />
          </div>
        </div>
      </div>
      <div v-if="maxSelected === 1 && finalSelected.length < maxSelected" class="fundodoo-picture-selector-button fundodoo-cursor" @click="dialogVisible = true">
        <i class="el-icon-picture fundodoo-picture-selector-button-icon" />
      </div>
      <div v-else-if="maxSelected > 1 && finalSelected.length < maxSelected" class="fundodoo-picture-selector-button fundodoo-cursor" @click="dialogVisible = true">
        <svg-icon icon-class="multi-image" class-name="fundodoo-picture-selector-button-icon" />
      </div>
    </div>
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      custom-class="fundodoo-dialog"
      :close-on-click-modal="false"
      @open="resetSelected"
    >
      <div class="fundodoo-picture-selector-body">
        <div class="fundodoo-picture-classification">
          <div class="fundodoo-picture-classification-body">
            <el-input
              v-model="filterText"
              placeholder="输入关键字进行过滤"
            />
            <el-tree
              ref="fundodooPCTree"
              node-key="id"
              class="fundodoo-picture-classification-filter-tree"
              :data="pcTreedata"
              :props="defaultProps"
              :expand-on-click-node="false"
              accordion
              :filter-node-method="filterNode"
            >
              <span slot-scope="{ node, data }" class="fundodoo-attachment-category-tree-actions">
                <span v-if="!data.pid && data.fundodooDisabled" @click.left.prevent="refreshAttachment(data)" @click.right.prevent="handleEditPanel(node,data,$event)">{{ node.label }}</span>
                <span v-else @click.left.prevent="refreshAttachment(data)">{{ node.label }}</span>
                <span v-if="data.id && data.fundodooDisabled">
                  <i title="编辑" class="el-icon-edit popover-i fundodoo-cursor" @click.prevent="handleEditPanel(node,data,$event)" />
                  <i title="删除" class="el-icon-delete popover-i fundodoo-cursor" @click.prevent="() => removeSAC(node, data)" />
                </span>
              </span>
            </el-tree>
            <div v-show="showEditPanel" :style="{left: editPanelLeftPosition,top: editPanelTopPosition}" class="fundodoo-pic-category-edit-panel ">
              <div class="show-edit-panel-close">
                <i title="关闭" class="el-icon-circle-close fundodoo-cursor" @click="closeSACpanel" />
              </div>
              <div class="fundodoo-center show-edit-panel-actions">
                <el-input v-model="attachmentCategory.name" placeholder="请输入名称" />
                <i v-if="!currentClickTreeData.hasParent && !showEdit" title="添加子类" class="el-icon-circle-plus-outline popover-i fundodoo-cursor" @click="appendSAC" />
                <i v-else title="保存" class="el-icon-finished popover-i fundodoo-cursor" @click="editSAC" />
              </div>
            </div>
          </div>
        </div>
        <div class="fundodoo-picture-container">
          <div class="fundodoo-picture-container-actions">
            <el-popover
              placement="bottom-start"
              width="400"
              trigger="click"
              popper-class="fundodoo-pic-popper"
            >
              <FundodooUpload :cid="uploadCid" />
              <el-button slot="reference" type="primary">上传图片</el-button>
            </el-popover>
            <el-button type="warning">移动分类</el-button>
            <el-button type="danger">删除图片</el-button>
          </div>
          <div v-infinite-scroll="loadMore" infinite-scroll-disabled="loadMoreDisabled" class="fundodoo-picture-container-body fundodoo-scrollBar">
            <el-image v-for="(item) in imageList" :key="item.id" class="fundodoo-image-el fundodoo-cursor" :class="{'fundodoo-picture-selected':selected.includes(item)}" fit="scale-down" :src="item.value" lazy @click.native="toggleSelect(item)">
              <div slot="error" class="fundodoo-image-load-error">
                <i class="el-icon-picture-outline" />
              </div>
            </el-image>
            <div class="fundodoo-picture-loadMore-info">
              <p v-if="loading">加载中...</p>
              <p v-if="noMore">没有更多了</p>
            </div>
          </div>

        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmCI">确 定</el-button>
      </div>
    </el-dialog>
  </div>

</template>

<script>
import { arr2arr, getServerStaticUrl } from '@/utils'
import { FundodooUpload } from '../fundodooUpload'
import { attachmentCategoryTree, addAttachmentCategory, updateAttachmentCategory,
  delAttachmentCategory, attachmentList } from '@/api/attachment'

export default {
  name: 'PictureSelector',
  components: { FundodooUpload },
  props: {
    dialogTitle: {
      type: String,
      default: '请选择图片'
    },
    maxSelected: {
      type: Number,
      default: 1
    },
    storagePic: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      dialogVisible: false,
      filterText: '',
      pcTreedata: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      imageList: [],
      currentClickTreeNode: null,
      currentClickTreeData: {},
      showEditPanel: false,
      showEdit: false,
      editPanelLeftPosition: '0px',
      editPanelTopPosition: '0px',
      attachmentCategory: {
        id: null,
        name: '',
        pid: null
      },

      uploadCid: null,
      pageParameter: {
        pageNum: 1,
        pageSize: 30,
        pid: null
      },

      loading: false,
      noMore: false,
      selected: [],
      finalSelected: []
    }
  },
  computed: {
    loadMoreDisabled() {
      return this.loading || this.noMore
    }
  },
  watch: {
    filterText(val) {
      this.$refs.fundodooPCTree.filter(val)
    }
  },
  mounted() {
    this.$nextTick(() => {
      if (this.storagePic && this.storagePic.length) {
        const tmpImgArray = this.storagePic.splice(process.env.VUE_APP_BASE_SEPARATION)
        for (let i = 0, len = tmpImgArray.length; i < len; i++) {
          const tmpImg = tmpImgArray[i]
          const tmpIndex = tmpImg.indexOf('?')
          const tmpItem = {}
          if (tmpIndex > -1) {
            tmpItem.id = tmpImg.substring(tmpIndex + 1)
            tmpItem.value = tmpImg.substring(0, tmpIndex)
          } else {
            tmpItem.id = new Date().getTime()
            tmpItem.value = tmpImg.substring(0, tmpIndex)
          }
          this.finalSelected.push(tmpItem)
        }
      }
      console.log('this.storagePic type:{}', this.storagePic.length)
      // arr2arr(this.storagePic, this.finalSelected)
    })
  },
  methods: {
    handleEditPanel(node, data, e) {
      this.currentClickTreeNode = node
      this.currentClickTreeData = data
      this.editPanelLeftPosition = (e.pageX + 38) + 'px'
      this.editPanelTopPosition = (e.pageY) + 'px'
      this.showEditPanel = true
      const tmpisEdit = e.button === 0
      this.showEdit = tmpisEdit
      if (tmpisEdit) {
        this.attachmentCategory.id = data.id
        this.attachmentCategory.pid = data.pid
        this.attachmentCategory.name = data.label
      } else {
        this.attachmentCategory.pid = data.id
      }
    },
    closeSACpanel() {
      this.currentClickTreeNode = {}
      this.currentClickTreeData = {}
      this.showEditPanel = false
      this.showEdit = false
      this.attachmentCategory.id = null
      this.attachmentCategory.pid = null
      this.attachmentCategory.name = ''
    },
    appendSAC() {
      const data = this.currentClickTreeData
      const { pid, name } = this.attachmentCategory

      addAttachmentCategory(this.attachmentCategory).then(res => {
        const newChild = {}
        newChild.id = res.data
        newChild.pid = pid
        newChild.label = name
        newChild.fundodooDisabled = true
        newChild.children = []
        newChild.hasChildren = false
        delete newChild.name
        if (data.id) {
          newChild.hasParent = true
          if (!data.children) {
            this.$set(data, 'children', [])
          }
          this.$refs.fundodooPCTree.append(newChild, data)
        } else {
          newChild.hasParent = false
          this.$refs.fundodooPCTree.append(newChild, null)
        }
        this.closeSACpanel()
      })
    },
    editSAC() {
      const data = this.currentClickTreeData
      const { name } = this.attachmentCategory
      updateAttachmentCategory(this.attachmentCategory).then(res => {
        data.label = name
        this.closeSACpanel()
      })
    },
    removeSAC(node, data) {
      this.$confirm(`确认删除${data.label}？`)
        .then(_ => {
          const { id } = data
          delAttachmentCategory(id).then(res => {
            data.fundodooDisabled = false
          })
        })
        .catch(_ => {})
    },
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    getPcTreedata() {
      attachmentCategoryTree().then(res => {
        const topAll = {
          id: null,
          label: '名称右键添加子节点',
          fundodooDisabled: true,
          pid: null
        }
        this.pcTreedata = res.data
        this.pcTreedata.unshift(topAll)
      })
    },

    refreshAttachment(obj, node, nodeObj) {
      this.uploadCid = obj.id
      this.imageList = []
      this.pageParameter.pageNum = 1
      this.noMore = false
      this.loading = false
      this.loadMore()
    },
    loadMore() {
      if (!this.noMore && !this.loading) {
        this.loading = true
        this.pageParameter.pid = this.uploadCid
        attachmentList(this.pageParameter).then(res => {
          this.pageParameter.pageNum += 1
          const tmpRecords = res.data.records
          const tmpLen = tmpRecords.length
          for (let i = 0; i < tmpLen; i++) {
            const tmpRecord = tmpRecords[i]
            const tmpImg = {
              id: tmpRecord.id,
              value: getServerStaticUrl(tmpRecord.sattDir, tmpRecord.name, tmpRecord.imageType)
            }
            this.imageList.push(tmpImg)
          }
          if (tmpLen < this.pageParameter.pageSize) {
            this.noMore = true
          }
          this.loading = false
        })
      }
    },
    toggleSelect(item) {
      const tmpIndex = this.selected.findIndex((value) => value === item)
      if (tmpIndex > -1) {
        this.selected.splice(tmpIndex, 1)
      } else {
        if (this.maxSelected === 1) {
          this.selected.pop()
        } else {
          const tmpLen = this.selected.length
          if (tmpLen >= this.maxSelected) {
            this.$message({
              message: `最多只能选择${this.maxSelected}张图片`,
              type: 'warning'
            })
            return
          }
        }
        this.selected.push(item)
      }
    },
    resetSelected() {
      arr2arr(this.finalSelected, this.selected)
      this.getPcTreedata()
      this.closeSACpanel()
    },
    selectChange() {
      arr2arr(this.selected, this.finalSelected)
      this.$emit('select-change', this.finalSelected)
    },
    previewSelected() {
      this.$message({
        message: `功能开发中`,
        type: 'warning'
      })
    },
    delSelected(item) {
      const tmpIndex = this.selected.findIndex((value) => value === item)
      if (tmpIndex > -1) {
        this.selected.splice(tmpIndex, 1)
        this.selectChange()
      }
    },
    confirmCI() {
      this.selectChange()
      this.dialogVisible = false
    }
  }
}
</script>

<style scoped>
  .fundodoo-pic-selector-button-preview,.fundodoo-pic-selected-preview-container {
    display: flex;
    align-items: center;
    justify-content: flex-start;
  }

  .fundodoo-picture-selector-button {
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .fundodoo-picture-selector-button,.fundodoo-pic-selected-preview {
    width: 58px;
    height: 58px;
    margin-right: 10px;
    border: 1px dashed #dcdfe6;
    border-radius: 5px;
  }

  .fundodoo-picture-selector-button-icon {
    font-size: 25px;
  }

  .fundodoo-picture-selector-body {
    display: flex;
    width: 100%;
    height: 58vh;
    border: 1px solid #dcdfe6;
    border-radius: 2px;
  }

  .fundodoo-preview-actions-container-modal {
    position: absolute;
    top: 5px;
    width: 56px;
    height: 56px;
    border: 0.5px dashed #dcdfe6;
    margin: 1px;
    color: #FFF;
    background-color: #FFF;
    opacity: 0;
    filter: alpha(opacity=0);
  }

  .fundodoo-preview-actions-container {
    display: flex;
    justify-content: center;
    align-items: center;
    position: absolute;
    top: 5px;
    width: 58px;
    height: 58px;
  }

  .fundodoo-preview-action {
    opacity: 0;
    color: #FFF;
  }

  .fundodoo-pic-selected-preview-item:hover > .fundodoo-preview-actions-container-modal {
    opacity: 0.5;
    filter: alpha(opacity=50);
  }

  .fundodoo-pic-selected-preview-item:hover > .fundodoo-preview-actions-container > .fundodoo-preview-action {
    opacity: 1;
    filter: alpha(opacity=100);
  }

  .fundodoo-picture-classification {
    width: 193px;
    height: 100%;
    border-right: 1px dashed #dcdfe6;
  }

  .fundodoo-picture-classification-body {
    width: 100%;
    height: 100%;
    padding: 10px;
    overflow-y: auto;
  }

  .fundodoo-picture-classification-filter-tree {
    margin-top: 10px;
  }

  .fundodoo-attachment-category-tree-actions {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  }

  .fundodoo-picture-container {
    width: calc(100% - 194px);
    height: 100%;
  }

  .fundodoo-pic-category-edit-panel {
    position: fixed;
    left: 30px;
    top: 129px;
    width: 178px;
    height: 58px;
    padding-right: 3px;
    padding-left: 3px;
    border: 1px solid #dcdfe6;
    background-color: #FFF;
    border-radius: 5px;
    z-index: 1;
  }

  .show-edit-panel-close {
    display: flex;
    flex-direction: row-reverse;
  }

  .show-edit-panel-actions {
    height: 38px;
  }

  .fundodoo-pic-popper {
    background-color: #d3dce6;
  }

  .fundodoo-picture-container-actions {
    width: 100%;
    height: 38px;
    margin-top: 10px;
    padding-left: 10px;
  }

  .fundodoo-picture-container-body {
    display: flex;
    flex-wrap: wrap;
    align-content: flex-start;
    height: calc(100% - 48px);
    padding-right: 10px;
    overflow-y: auto;
  }

  .fundodoo-image-el {
    width: 108px;
    height: 108px;
    margin: 0px 0 10px 10px;
    padding: 0.5px;
    border: 0.5px dashed #dcdfe6;
  }

  .fundodoo-picture-selected {
    border: 0.5px solid skyblue;
  }

  .fundodoo-picture-loadMore-info {
    margin-left: 10px;
    width: 100%;
    text-align: center;
    color: #d3dce6;
  }

  .popover-i {
    margin-left: 6px;
  }

</style>
